'use strict';

/* Controllers */
// signin controller
app.controller('GoodsController', ['dbUtils','$rootScope', '$scope','$modal', '$state', '$cookieStore', 'GoodsService', function (dbUtils,$rootScope, $scope,$modal, $state, $cookieStore, goodsService) {
    $scope.categories = [];

    $scope.$on('showImg',function(event,src){
        dbUtils.showImg(src);
    });


    goodsService.getCategoryList().then(function (response) {
        if (response.code == 0) {
            $scope.categories.push({group:'',key:'',value:'全部'});
            for (var i = 0; i < response.data.length; i++) {
                var cat = response.data[i];
                for (var j = 0; j < cat.subCategories.length; j++) {
                    var secondCat = cat.subCategories[j];
                    $scope.categories.push({group: cat.name, key: secondCat.id, value: secondCat.name});
                }
            }
        }
    });

    var formGridOptions = {
        form: {
            settings: {
                cols: 3
            },
            fields: [
                {name: "goodsName", label: "商品名称", type: "text", labelCols: "4"},
                {name: "categoryId", label: "商品分类", type: "groupSelect", labelCols: "4", items: $scope.categories,cols:6},
                {
                    name: "status",
                    label: "商品状态",
                    labelCols: "4",
                    type: "select",
                    items: [{
                        "key": "0",
                        "value": "下架"
                    }, {
                        "key": "1",
                        "value": "上架"
                    },{
                        "key": "-1",
                        "value": "删除"
                    }]
                }
            ]
        },
        grid: {
            settings: {
                transCode: "/goods/pageList",
                autoLoad: true,
                pageSize:10,
                showCheckBox: true
            },
            header: [
                {name: "商品名称", field: "name",class: "linka",width:"10%"},
                {name: "商品图片", field: "goodsThumb",compile:true,width:"20%"},
                {name: "商品分类", field: "category"},
                {name: "商品规格", field: "standard"},
                {name: "商品原价", field: "shopPrice"},
                {name: "商品现价", field: "promotePrice"},
                {name: "商品条码", field: "goodsSn"},
                {name: "商品状态", field: "status"}
            ],
            rowOperation: {show: true, width: "20%"}
        }
    }

    var formGridEvents = {
        grid: {
            fieldEvents: {
                "nameClick": function (row) {
                    editModal(row,true);
                },
                "goodsThumbFormat": function (value, row) {
                    if (value) {
                        return "<a ng-click=\"publishEvent('showImg','"+value+"')\">点击查看</a>";
                    };
                },
                "statusFormat": function(value,row){
                    if(value == '0'){
                        return '下架';
                    }else if(value == '1'){
                        return '上架';
                    }else{
                        return '已删除';
                    }
                },
                "shopPriceFormat": function(value,row){
                    if(value && value>0){
                        return value/100;
                    }
                },
                "promotePriceFormat":function(value,row){
                    if(value && value>0){
                        return value/100;
                    }
                }
            },

            rowEvents: [
                {
                    name: "编辑", class: "btn-success",
                    click: function (row) {
                        editModal(row);
                    }
                },
                {
                    name: "删除", class: "btn-danger",
                    click: function (row) {
                        goodsService.updateStatus([row.goodsId],-1).then(function(response){
                            if(response.code == 0){
                                $scope.dbFormGrid.reLoadData();
                            }
                        });
                    }
                }
            ],
            operationEvents: [{
                name: "删除", class: "btn-danger", icon: "trash-o", click: function (rows) {
                    var goodsIds = [];
                    for(var i=0;i<rows.length;i++){
                        goodsIds.push(rows[i].goodsId);
                    }
                    goodsService.updateStatus(goodsIds,-1).then(function(response){
                        if(response.code == 0){
                            $scope.dbFormGrid.reLoadData();
                        }
                    });
                }
            },{
                name: "下架", class: "btn-info", icon: "pencil", click: function (rows) {
                    var goodsIds = [];
                    for(var i=0;i<rows.length;i++){
                        goodsIds.push(rows[i].goodsId);
                    }
                    goodsService.updateStatus(goodsIds,0).then(function(response){
                        if(response.code == 0){
                            $scope.dbFormGrid.reLoadData();
                        }
                    });
                }
            },{
                name: "上架", class: "btn-primary", icon: "html5", click: function (rows) {
                    var goodsIds = [];
                    for(var i=0;i<rows.length;i++){
                        goodsIds.push(rows[i].goodsId);
                    }
                    goodsService.updateStatus(goodsIds,1).then(function(response){
                        if(response.code == 0){
                            $scope.dbFormGrid.reLoadData();
                        }
                    });

                }
            },{
                name: "发布新商品", class: "btn-success", icon: "css3", click: function (rows) {
                    openModal();
                }
            }]
        }
    };

    $scope.dbFormGrid = {options: formGridOptions, events: formGridEvents};


    //发布新商品
    function openModal(source) {
        var instance = $modal.open({
            animation: true,
            templateUrl: 'tpl/goods/addGoods.html',
            controller: 'GoodsEditController',
            size: "lg",
            backdrop: "static",
            resolve: {
                source: function () {
                    return source;
                }
            }
        });
        instance.result.then(function () {
            $scope.dbFormGrid.reLoadData();
        });
    }


    //编辑modal
    function editModal(source,view) {
        var instance = $modal.open({
            animation: true,
            templateUrl: 'tpl/goods/addGoods.html',
            controller: 'GoodsEditController',
            size: "lg",
            backdrop: "static",
            resolve: {
                source: function () {
                    return {goodsId:source.goodsId,view:view}
                }
            }
        });
        instance.result.then(function () {
            $scope.dbFormGrid.reLoadData();
        });
    }
}]);


app.controller('GoodsEditController', ['dbUtils','$scope','$modalInstance', '$state','Upload', 'GoodsService','source', function (dbUtils,$scope,$modalInstance, $state,upload, goodsService,source) {
    $scope.info={};
    $scope.goodsImgs=[];
    $scope.categories=[];
    var newRecord = false;

    //区分不同编辑状态
    if (angular.isUndefined(source)) {
        newRecord = true;
    } else if(source.view){
        $scope.formDisabled = true;
        $scope.editData = true;
    }else{
        $scope.formDisabled = false;
        $scope.editData = true;
    }

    if(!newRecord){
        console.log(source);
        goodsService.getGoods(source.goodsId).then(function(response){
            console.log(response);
            if(response.code == 0){
                $scope.goodsImgs = response.data.goodsImg && response.data.goodsImg.split(",");
                response.data.categoryId = {key:response.data.categoryId,value:response.data.category};
                response.data.shopPrice = (response.data.shopPrice && response.data.shopPrice>0) ? response.data.shopPrice/100:'0';
                response.data.promotePrice = (response.data.promotePrice && response.data.promotePrice>0) ? response.data.promotePrice/100:'0';
                $scope.info = response.data;

            }
        });
    }


    $scope.upload = function (file, model) {
        if (file) {
            upload.upload({
                url: '/upload/goods/img',
                fields: {'type': 'thumb'},
                file: file
            }).progress(function (evt) {

            }).success(function (data, status, headers, config) {
                $scope['info'][model] = data.data;
            }).error(function (data, status, headers, config) {
                dbUtils.error("上传失败", "提示");
            })
        }
    };
    $scope.removeImg = function (model) {
        $scope['info'][model] = null;
    };
    $scope.uploadMulti =function (files) {
        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {
                if($scope.goodsImgs.length > 10){
                    return;
                }
                upload.upload({
                    url: '/upload/goods/img',
                    fields: {'type': 'image'},
                    file: files[i]
                }).progress(function (evt) {

                }).success(function (data, status, headers, config) {
                    $scope['goodsImgs'].push(data.data);
                }).error(function (data, status, headers, config) {
                    dbUtils.error("上传失败", "提示");
                })
            }
        }
    };
    $scope.removeMultiImg = function(model,i){
        $scope[model].splice(i,1);
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    $scope.showImg = function (event) {
        dbUtils.showImg(event.target.currentSrc);
    };


    goodsService.getCategoryList().then(function (response) {
        if (response.code == 0) {
            for (var i = 0; i < response.data.length; i++) {
                var cat = response.data[i];
                for (var j = 0; j < cat.subCategories.length; j++) {
                    var secondCat = cat.subCategories[j];
                    $scope.categories.push({group: cat.name, key: secondCat.id, value: secondCat.name});
                }
            }
        }
    });

    $scope.submitApply = function(){
        if($scope.form.$invalid){
            return;
        }
        var data = angular.copy($scope.info);
        if($scope.goodsImgs.length > 0){
            data.goodsImg = $scope.goodsImgs.join(",");
        }
        if(data.categoryId){
            data.categoryId = $scope.info.categoryId.key;
        }
        if(data.shopPrice){
            data.shopPrice = Math.ceil($scope.info.shopPrice*100);
        }
        if(data.promotePrice){
            data.promotePrice = Math.ceil($scope.info.promotePrice*100);
        }
        if(newRecord){
            goodsService.addGoods(data).then(function(response){
                if(response.code == 0){
                    dbUtils.success("提交成功！","提示");
                    $modalInstance.close();
                }else{
                    dbUtils.warning(response.message,"提示");
                }
            });
        }else{
            data.goodsId = source.goodsId;
            goodsService.setGoods(data).then(function(response){
                if(response.code == 0){
                    dbUtils.success("提交成功！","提示");
                    $modalInstance.close();
                }else{
                    dbUtils.warning(response.message,"提示");
                }
            });
        }
    }

}]);